#!/usr/bin/perl
#
# Fix user record inconsistencies
#
# - f_mtime >= max(f_ctime, logintime)
# - logintime >= f_ctime
# - state is in legal-state-list, set to "ok" otherwise
# - privacy is set (FIXME: Not done yet - needs other pieces)
#
use Counter;
use Fcntl;

$users = Counter::open(O_RDWR);

$expr = shift;
if (!$expr) {
    $expr = "1 limit 10";
}
# For reasons of memory consumption, impose a limit
# approx 7 M for 1000 records on x86 - try 5000 limit
if ($expr !~ /limit \d+$/) {
    $expr .= " limit 5000";
    warn "Imposing limit 5000\n";
}
@users = $users->select($expr);
$updatecount = 0;
for $user (@users) {
    $key = $user->key();
    if ($user->{f_mtime} lt $user->{f_ctime}) {
	warn "$key: Bumping f_mtime from $$user{f_mtime} to $$user{f_ctime}\n";
	$user->{f_mtime} = $user->{f_ctime};
	$dosomething = 1;
    }
    if ($user->{logintime} lt $user->{f_ctime}) {
	warn "$key: Bumping logintime from $$user{logintime} to $$user{f_ctime}\n";
	$user->{logintime} = $user->{f_ctime};
	$dosomething = 1;
    }
    if (!$Counter::User::states{$$user{state}}) {
	warn "$key: Changing state from $$user{state} to ok\n"
	    if $$user{state}; # don't bother warning about the blank
	$user->{state} = "ok";
	$dosomething = 1;
    }
    if ($dosomething) {
	$user->patch(); # Do NOT update timestamp, log and so forth
	++ $updatecount;
    }
}
print @users+0, " users, $updatecount updates\n";
